package com.qef.com.mmovie.fragment.laugh_img;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.transition.Fade;
import android.transition.Slide;
import android.util.Log;
import android.view.View;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.ButtonEnum;
import com.orhanobut.logger.Logger;
import com.qef.com.mmovie.MainActivity;
import com.qef.com.mmovie.R;
import com.qef.com.mmovie.base.BaseFragment;
import com.qef.com.mmovie.base.DetailTransition;
import com.qef.com.mmovie.components.EventUtil;
import com.qef.com.mmovie.entity.LaughImgEntity;
import com.qef.com.mmovie.mvp.activity.VideoDetailActivity;
import com.qef.com.mmovie.mvp.adapter.LaughImgAdapter;
import com.qef.com.mmovie.mvp.adapter.RecyclerViewAnimator;
import com.qef.com.mmovie.mvp.adapter.VideoAdapter;
import com.qef.com.mmovie.presenter.LaughImgPresenter;
import com.qef.com.mmovie.presenter.contract.LauthImgContract;
import com.qef.com.mmovie.utils.AnimatiorUtils;
import com.qef.com.mmovie.widget.BuilderManager;
import com.qef.com.mmovie.widget.EndLessOnScrollListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * Created by guangjiego on 2017/3/31.
 */

public class LaughImgHomeFragment extends BaseFragment<LaughImgPresenter> implements LauthImgContract.View {
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    LaughImgAdapter adapter;
    List<LaughImgEntity.DataEntity> dataBeanxes;
    @BindView(R.id.bmb)
    BoomMenuButton bmb;
    int page = 1, size = 10, cateid = 6;
    private int[] cateId = {8, 7, 6, 23, 18, 10, 16, 45, 11};
    private int[] cateIdNameId = {R.string.cate8, R.string.cate7, R.string.cate6, R.string.cate23, R.string.cate18, R.string.cate10,
            R.string.cate16
            , R.string.cate45, R.string.cate11};
    boolean isScroll = true;

    public static LaughImgHomeFragment newInstance() {
        Bundle bundle = new Bundle();
        LaughImgHomeFragment videoFragment = new LaughImgHomeFragment();
        videoFragment.setArguments(bundle);
        return videoFragment;
    }

    @Override
    public void showContent(LaughImgEntity laughImgEntity) {
        Logger.i("----------");
        if (refresh.isRefreshing()) {
            refresh.setRefreshing(false);
            dataBeanxes.clear();
            adapter.clear();
            adapter.addAll(laughImgEntity.getData());
//            recycler.setAdapter(adapter);
        } else {
            if (null != laughImgEntity.getData())
                adapter.addAll(laughImgEntity.getData());
        }
        if (null != laughImgEntity.getData())
            dataBeanxes.addAll(laughImgEntity.getData());
        adapter.setOnItemClickListener((position, view, vh) -> {
            Pair<View, String> imagePair = Pair.create(((LaughImgAdapter.MyHolder) vh).imageView, getString(R.string.image_transition));
            Pair<View, String> textPair = Pair.create(((LaughImgAdapter.MyHolder) vh).textView, getString(R.string.title));
            Pair<View, String> textPairx = Pair.create(((LaughImgAdapter.MyHolder) vh).description, getString(R.string.description));
            ActivityOptionsCompat compat = ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(),
                    imagePair, textPair, textPairx);
            startActivity(new Intent(getActivity(), LaughImgDetailFragment.class).
                            putExtra("dataBean", (Parcelable) dataBeanxes.get(position))
                    , compat.toBundle());
//            Intent intent = new Intent();
//            intent.putExtra("dataBean", (Parcelable) dataEntity);
//            intent.setClass(getActivity(), LaughImgDetailFragment.class);
//            startActivity(intent);
//
//            startChildFragment(dataBeanxes.get(position), (LaughImgAdapter.MyHolder) vh);
        });

    }

    @Override
    public void error(Throwable throwable) {

    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.video_home_fragment;
    }

    @Override
    protected void initEventAndData() {
        EventUtil.register(this);
        initBoomMenu();
        refresh.setBackgroundColor(getResources().getColor(R.color.page3));
//        // 测试 SDK 是否正常工作的代码
//        AVObject testObject = new AVObject("TestObject");
//        testObject.put("words", "Hello World!");
//        testObject.saveInBackground(new SaveCallback() {
//            @Override
//            public void done(AVException e) {
//                if (e == null) {
//                    Log.d("saved", "success!");
//                }
//            }
//        });


        mPresenter.getLaughList(page, size, cateid);
        refresh.setProgressViewOffset(false, 100, 200);
        refresh.setRefreshing(true);
        LinearLayoutManager layout = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        refresh.setOnRefreshListener(() -> {
            refresh.setRefreshing(true);
            mPresenter.getLaughList(page = 1, size, cateid);
        });


        recycler.setLayoutManager(layout);
        dataBeanxes = new ArrayList<>();
        adapter = new LaughImgAdapter(getActivity(), dataBeanxes);
        recycler.setAdapter(RecyclerViewAnimator.setAnimator(adapter));
        recycler.addOnScrollListener(new EndLessOnScrollListener(layout, 0) {
            @Override
            public void onLoadMore() {
                page++;
                mPresenter.getLaughList(page, size, cateid);
            }
        });
//        mPresenter.getLaughList();
//        getParentFragment().req
    }

    private void startChildFragment(LaughImgEntity.DataEntity dataEntity, LaughImgAdapter.MyHolder vh) {
        EventUtil.sendEvent(true + "");
//        LaughImgDetailFragment fragment = LaughImgDetailFragment.newInstance(
//                dataEntity);
        // 这里是使用SharedElement的用例
        Intent intent = new Intent();
        intent.putExtra("dataBean", (Parcelable) dataEntity);
        intent.setClass(getActivity(), LaughImgDetailFragment.class);
        startActivity(intent);
//        // LOLLIPOP(5.0)系统的 SharedElement支持有 系统BUG， 这里判断大于 > LOLLIPOP
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
//            setExitTransition(new Fade());
//            fragment.setEnterTransition(new Slide());
//            fragment.setSharedElementReturnTransition(new DetailTransition());
//            fragment.setSharedElementEnterTransition(new DetailTransition());
//
//            // 25.1.0以下的support包,Material过渡动画只有在进栈时有,返回时没有;
//            // 25.1.0+的support包，SharedElement正常
//            fragment.transaction()
//                    .addSharedElement(vh.imageView, getString(R.string.image_transition))
////                        .addSharedElement(((VideoAdapter.MyHolder) vh).textView,"tv")
//                    .commit();
//        }
//        start(fragment);
//        ((MainActivity) getActivity()).hindbar();
    }

    private void initBoomMenu() {
        bmb.setButtonEnum(ButtonEnum.TextInsideCircle);
        for (int i = 0; i < bmb.getPiecePlaceEnum().pieceNumber(); i++)
            bmb.addBuilder(BuilderManager.getTextInsideCircleButtonBuilder().listener(index -> {
                mPresenter.getLaughList(page = 1, size, cateid = cateId[index]);
                refresh.setRefreshing(true);
            }).normalTextRes(cateIdNameId[i]));
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEvent(int msg) {
        if (msg == 0) {
            if (!isScroll) {
                AnimatiorUtils.setZoom(bmb, 0, 1);
                isScroll = true;
            }
        } else {
            if (isScroll) {
                AnimatiorUtils.setZoom(bmb, 1, 0);
                isScroll = false;
            }

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventUtil.unregister(this);
    }
}
